"""
@author: Zhang Wenzhou
@file: stuapi.py
@time: 2023/3/4 0004 10:51:48
"""
"""
restful -- 接口设计风格
REST 表现层状态转化   

url 当作一种资源，通过http动作来实现对这个资源

restful api
url资源         http方法
/v1/student     GET     查询所有
                POST    新增
/v1/student/id  GET     查询一个
                DELETE  删一个
                PUT     修改一个
"""

from flask import Blueprint, request
from flask_restful import Resource, Api
from model.user import StuIf
from model import db
from libs.response import response_data

stuapi_bp = Blueprint("stuapi_bp", __name__, url_prefix="/v1")
api = Api(stuapi_bp)

class StudentView(Resource):
    def get(self, id=None):
        # 能获取到id返回一个，获取不到id，返回所有
        try:
            if id is not None:
                stu = StuIf.query.get(int(id))
                tmp_dict = dict(stu)
                tmp_dict["class_name"] = stu.class_obj.class_name
                return response_data(message="获取数据成功", data=tmp_dict)
            else:
                stu_lst = []
                for i in StuIf.query.all():
                    stu_lst.append(dict(i))
                return response_data(message="获取数据成功", data=stu_lst)
        except:
            return response_data(code=1, message="获取数据失败！")

    def post(self):
        try:
            message = request.json
            name = message['name']
            sex = message['sex']
            age = message['age']
            #     rom   类--表    对象--一行记录
            stu = StuIf(name=name,
                          sex=sex,
                          age=age)
            db.session.add(stu)  # 要修改的对象加入暂存区
            db.session.commit()  # 提交暂存区里的对象
            return response_data(message="添加信息成功！")
        except:
            return response_data(code=1, message="添加信息失败！")

    def put(self, id):
        try:
            # 查询:找到要修改的对象
            stu = StuIf.query.get(int(id))
            # 找不到对象就返回None
            if stu:
                stu.name = request.json.get("name")
                stu.sex = request.json.get("sex")
                stu.age = request.json.get("age")
                db.session.add(stu)
                db.session.commit()
                return response_data(message="修改信息成功")
        except:
            return response_data(code=1, message="修改信息失败！")

    def delete(self, id):
        try:
            stu = StuIf.query.get(int(id))
            if stu:
                db.session.delete(stu)
                db.session.commit()
                return response_data(message="删除信息成功")
        except:
            return response_data(code=1, message="删除信息失败！")
api.add_resource(StudentView, "/student")
# endpoint 全局唯一
api.add_resource(StudentView, "/student/<int:id>", endpoint="student_view")

